home *** CD-ROM | disk | FTP | other *** search
/ Reverse Code Engineering RCE CD +sandman 2000 / ReverseCodeEngineeringRceCdsandman2000.iso / RCE / Ebooks / Thinking in C++ V2 / C18 / Strfile.cpp < prev    next >
Encoding:
C/C++ Source or Header  |  2000-05-25  |  1.2 KB  |  43 lines

  1. //: C18:Strfile.cpp
  2. // From Thinking in C++, 2nd Edition
  3. // Available at http://www.BruceEckel.com
  4. // (c) Bruce Eckel 1999
  5. // Copyright notice in Copyright.txt
  6. // Stream I/O with files
  7. // The difference between get() & getline()
  8. #include "../require.h"
  9. #include <fstream>  
  10. #include <iostream>
  11. using namespace std;
  12.  
  13. int main() {
  14.   const int sz = 100; // Buffer size;
  15.   char buf[sz];
  16.   {
  17.     ifstream in("Strfile.cpp"); // Read
  18.     assure(in, "Strfile.cpp"); // Verify open
  19.     ofstream out("Strfile.out"); // Write
  20.     assure(out, "Strfile.out");
  21.     int i = 1; // Line counter
  22.  
  23.     // A less-convenient approach for line input:
  24.     while(in.get(buf, sz)) { // Leaves \n in input
  25.       in.get(); // Throw away next character (\n)
  26.       cout << buf << endl; // Must add \n
  27.       // File output just like standard I/O:
  28.       out << i++ << ": " << buf << endl;
  29.     }
  30.   } // Destructors close in & out
  31.  
  32.   ifstream in("Strfile.out");
  33.   assure(in, "Strfile.out");
  34.   // More convenient line input:
  35.   while(in.getline(buf, sz)) { // Removes \n
  36.     char* cp = buf;
  37.     while(*cp != ':')
  38.       cp++;
  39.     cp += 2; // Past ": "
  40.     cout << cp << endl; // Must still add \n
  41.   }
  42. } ///:~
  43.